import { DataSource } from 'typeorm';
import { getConfig } from '../utils/index';
import { NamingStrategy } from './naming.strategies';
import { Site } from '../../../../apps/low-code-test/src/site/entities/site.entity';

const { MONGODB_CONFIG, MYSQL_CONFIG } = getConfig();
console.log(MYSQL_CONFIG);

const MONGODB_DATABASE_CONFIG = {
  ...MONGODB_CONFIG,
  entities: [Site, `dist/**/*.${MONGODB_CONFIG.entities}.entity.js`],
};

const MYSQL_DATABASE_CONFIG = {
  ...MYSQL_CONFIG,
  namingStrategy: new NamingStrategy(),
  entities: [`dist/**/*.${MYSQL_CONFIG.entities}.entity.js`],
};

const MONGODB_DATA_SOURCE = new DataSource(MONGODB_DATABASE_CONFIG);
const MYSQL_DATA_SOURCE = new DataSource(MYSQL_DATABASE_CONFIG);

// 数据库注入
export const DatabaseProviders = [
  {
    provide: 'MONGODB_DATA_SOURCE',
    useFactory: async () => {
      try {
        if (!MONGODB_DATA_SOURCE.isInitialized) {
          console.log('正在连接 MongoDB...');
          await MONGODB_DATA_SOURCE.initialize();
          console.log('MongoDB 连接成功');
        }
        return MONGODB_DATA_SOURCE;
      } catch (error) {
        console.error('MongoDB 连接失败:', error);
        throw error;
      }
    },
  },
  {
    provide: 'MYSQL_DATA_SOURCE',
    useFactory: async () => {
      try {
        if (!MYSQL_DATA_SOURCE.isInitialized) {
          console.log('正在连接 MySQL...');
          await MYSQL_DATA_SOURCE.initialize();
          console.log('MySQL 连接成功');
        }
        return MYSQL_DATA_SOURCE;
      } catch (error) {
        console.error('MySQL 连接失败:', error);
        throw error;
      }
    },
  },
];
